package com.leo.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author wangss
 * @date 2023/02/13 20:16
 * @description
 **/
@Slf4j
public class MybatisUtils {

    private static final String resource = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;

    static {
        initSqlSessionFactory();
    }

    private static void initSqlSessionFactory() {
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            log.error("mybatis加载失败，原因：{}", e.getMessage());
        }
    }

    public static SqlSession getSqlSession() {
        if (null == sqlSessionFactory) {
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        if (null == sqlSessionFactory) {
            initSqlSessionFactory();
        }
        return sqlSessionFactory;
    }

}
